﻿using System.Windows.Forms;
using HDM.NexusEngine.Core;
using HDM.NexusEngine.Input;
using Tao.OpenGl;

namespace HDM.NexusEngine.Shooter.GameStates
{
    public class GameOverState : IGameObject
    {
        private const double TIME_OUT = 4;
        private double _countDown = TIME_OUT;
        private readonly StateSystem _system;
        private readonly InputManager _input;
        private readonly PersistantGameData _gameData;
        private readonly Renderer _renderer = new Renderer();
        private readonly Text _titleWin;
        private readonly Text _blubWin;
        private readonly Text _titleLose;
        private readonly Text _blurbLose;

        public GameOverState(PersistantGameData data, StateSystem system, InputManager input, Font generalFont, Font titleFont)
        {
            _gameData = data;
            _system = system;
            _input = input;

            _titleWin = new Text("Complete!", titleFont);
            _blubWin = new Text("Congratulations, you won!", generalFont);
            _titleLose = new Text("Game Over!", titleFont);
            _blurbLose = new Text("Please try again...", generalFont);

            FormatText(_titleWin, 300);
            FormatText(_blubWin, 200);
            FormatText(_titleLose, 300);
            FormatText(_blurbLose, 200);
        }

        private void FormatText(Text text, int yPosition)
        {
            text.SetPosition(-text.Width/2, yPosition);
            text.SetColor(new Color(0, 0, 0, 1));
        }

        public void Update(double elapsedTime)
        {
            _countDown -= elapsedTime;

            if (_countDown <= 0 || 
                (_input.Controller != null && _input.Controller.ButtonA.Pressed) ||
                _input.Keyboard.IsKeyPressed((Keys.Enter)))
            {
                Finish();
            }
        }

        private void Finish()
        {
            _gameData.JustWon = false;
            _system.ChangeState("start_menu");
            _countDown = TIME_OUT;
        }

        public void Render()
        {
            Gl.glClearColor(1, 1, 1, 0);
            Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);

            if (_gameData.JustWon)
            {
                _renderer.DrawText(_titleWin);
                _renderer.DrawText(_blubWin);
            }
            else
            {
                _renderer.DrawText(_titleLose);
                _renderer.DrawText(_blurbLose);
            }

            _renderer.Render();
        }
    }
}